import os
from datetime import timezone

from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.db import models
# Create your models here.
class Task(models.Model):
    STATUS_CHOICES = (
        (-1, "错误"),
        (0, "未开始"),
        (1, "执行中"),
        (2, "已完成"),
    )
    user = models.ForeignKey(User, on_delete=models.DO_NOTHING)
    task_name = models.CharField(max_length=100, null=False, verbose_name="任务名称", help_text="请输入一个名称用来区分不同的任务")
    file = models.FileField(upload_to='uploads/')  # 用 file 字段代替 file_name 和 file_url
    file_name = models.CharField(max_length=255, blank=True)
    file_url = models.URLField(max_length=500, blank=True)
    file_name = models.CharField(max_length=200, verbose_name="文件名称")
    file_url = models.CharField(max_length=200, verbose_name="文件地址")
    status = models.IntegerField(default=0, verbose_name="任务状态", choices=STATUS_CHOICES) #0等待执行，1执行中，2执行完毕
    result_img_name = models.CharField(max_length=200, default="", verbose_name="图片结果")
    result_xlsx_name = models.CharField(max_length=200, default="", verbose_name="表格结果")
    pub_date = models.DateTimeField("发布时间", auto_now_add=True)

    def clean(self):
        # 限制文件类型为 .txt
        if self.file:
            ext = os.path.splitext(self.file.name)[1]  # 获取文件扩展名
            # 定义允许的图片扩展名列表
            ALLOWED_IMAGE_EXTENSIONS = ['.zip', '.rar', '.7z']
            if ext not in ALLOWED_IMAGE_EXTENSIONS:
                raise ValidationError("仅支持 ZIP/RAR/7z 压缩包")

            # 检查文件大小（以字节为单位）
            max_size_mb = 200
            if self.file.size > max_size_mb * 1024 * 1024:
                raise ValidationError(f"文件大小不能超过 {max_size_mb}MB。")

    def save(self, *args, **kwargs):
        if self.file:
            self.file_name = self.file.name
            self.file_url = self.file.url
        super().save(*args, **kwargs)

    def __str__(self):
        return f"{self.task_name} (用户: {self.user.username})"